package com.luoqiu.cinema.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.luoqiu.cinema.common.Result;
import com.luoqiu.cinema.entity.UserInfo;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;

import javax.annotation.Resource;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

/**
 * @author 洛秋y
 * @date 2020/11/27 14:04
 */
public class SunckFormAuthenticationFilter  extends FormAuthenticationFilter {


    @Resource
    private ObjectMapper objectMapper;
    /**
     * 登录认证成功后回调方法
     * @param request
     * @param response
     * @throws Exception
     */
    @Override
    protected boolean onLoginSuccess(AuthenticationToken token, Subject subject,
                                     ServletRequest request, ServletResponse response) throws Exception {
        response.setContentType("application/json");
        response.setCharacterEncoding("utf-8");
        UserInfo user = (UserInfo) subject.getPrincipal();
        Result<UserInfo> success = Result.success(user);
        response.getWriter().write(objectMapper.writeValueAsString(success));
        return false;
    }

    /**
     * 登录失败后回调方法
     *
     */
    @Override
    protected boolean onLoginFailure(AuthenticationToken token, AuthenticationException e,
                                     ServletRequest request, ServletResponse response) {

        return true;
    }

}
